<template>
    <div class="app-container">
        <el-table
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
        >
            <el-table-column align="center" label="编号" width="95">
                <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="标题">
                <template slot-scope="scope">
                    <span v-if="scope.row.edit">
                        <el-input v-model="scope.row.title" placeholder="请输入内容" size="medium"/>
                    </span>
                    <span v-else>{{ scope.row.title }}</span>
                </template>
            </el-table-column>
            <el-table-column label="图片" width="110">
                <template slot-scope="scope">
                    <span v-if="scope.row.edit">
                        <el-input v-model="scope.row.imgUrl" placeholder="请输入内容" size="medium"/>
                    </span>
                    <span v-else>
                        <img :src="scope.row.imgUrl" class="img-size">
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="描述" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.edit">
                        <el-input v-model="scope.row.description" placeholder="请输入内容" size="medium"/>
                    </span>
                    <span v-else>{{ scope.row.description }}</span>
                </template>
            </el-table-column>
            <el-table-column label="价格(元)" width="110" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.edit">
                        <el-input v-model="scope.row.price" placeholder="请输入内容" size="medium"/>
                    </span>
                    <span v-else>{{ scope.row.price }}</span>
                </template>
            </el-table-column>
            <el-table-column class-name="status-col" label="库存(件)" width="110" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.edit">
                        <el-input v-model="scope.row.stock" placeholder="请输入内容" size="medium"/>
                    </span>
                    <span v-else>
                        <!--<el-tag :type="scope.row.status | statusFilter">{{ scope.row.stock }}</el-tag>-->
                        {{ scope.row.stock }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="销量(件)" width="110">
                <template slot-scope="scope">
                    <i class="el-icon-time"/>
                    <span>{{ scope.row.sales }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="created_at" label="操作" width="160">
                <template slot-scope="scope">
                    <el-button v-if="!scope.row.edit" type="info" icon="el-icon-edit" circle @click="handleEdit(scope.row,scope.$index)" />
                    <el-button v-if="!scope.row.edit" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row,scope.$index)" />
                    <el-button v-if="scope.row.edit" type="success" icon="el-icon-check" circle @click="handleSave(scope.row,scope.$index)" />
                    <el-button v-if="scope.row.edit" type="danger" icon="el-icon-close" circle @click="handleCancel(scope.row,scope.$index)" />
                </template>
            </el-table-column>
        </el-table>
        <div class="el-table-add-row" style="width: 99.2%;" @click="handleAdd"><span>+ 添加</span></div>
    </div>
</template>

<script>
    import { getList, addItem, updateItem, deleteItem } from '@/api/item'
    export default {
        filters: {
            statusFilter(status) {
                const statusMap = {
                    published: 'success',
                    draft: 'gray',
                    deleted: 'danger'
                }
                return statusMap[status]
            }
        },
        data() {
            return {
                list: null,
                listLoading: true,
                edit: false, // 是否编辑状态
                backupItem: null // 选中行
            }
        },
        created() {
            this.fetchData()
        },
        methods: {
            fetchData() {
                console.log('重新查询商品列表')
                this.listLoading = true
                const timestamp = new Date().getTime()
                const listQuery = { t: timestamp }
                getList(listQuery).then(response => {
                    this.list = response.data.map((item) => {
                        item.edit = false
                        return item
                    })
                    console.log('itemList', this.list)
                    this.listLoading = false
                })
            },
            handleEdit(row, index) {
                if (this.isEdit()) {
                    return
                }
                // 先将当前行备份
                this.backupItem = row
                // 再将 编辑状态改变
                row.edit = true
                // console.log(index, row)
                // this.validate(row)
                //
                // 重新查询数据  关闭编辑状态
                // this.fetchData()
            },
            handleDelete(row, index) {
                if (this.isEdit()) {
                    return
                }
                console.log(row, index)
                deleteItem(row.id).then(response => {
                    console.log('deleteItem', response)
                    // 重新查询数据  关闭编辑状态
                    this.fetchData()
                })
            },
            handleSave(row, index) {
                console.log('table', index, row)
                if (!this.validate(row)) {
                    return
                }
                console.log(row.id)
                // 判断是添加还是修改
                if (typeof (row.id) === 'undefined') {
                    // 数据提交
                    addItem(row).then(response => {
                        console.log('addItem', response)
                        this.fetchData()
                    })
                } else {
                    updateItem(row).then(response => {
                        console.log('updateItem', response)
                        this.fetchData()
                    })
                }
                // 重新查询数据  关闭编辑状态
                // **此处会产生十分严重的问题，因为这里是异步添加和修改会导致先执行查询后执行添加或修改**
                // this.fetchData()
            },
            handleCancel(row, index) {
                // 如果是新增 直接删除
                if (typeof (row.id) === 'undefined') {
                    this.list.splice(index, 1)
                } else {
                    // 否则 恢复备份
                    row = this.backupItem
                    row.edit = false
                }
            },
            // 添加账号
            handleAdd() {
                if (this.isEdit()) {
                    return
                }
                const newRow = { 'title': '', 'description': '', 'price': 0, 'stock': 0, 'sales': 0, 'edit': true }
                this.list.push(newRow)
                this.select = JSON.parse(JSON.stringify(newRow))
            },
            // 是否存在正在编辑的项目
            isEdit() {
                for (const i of this.list) {
                    if (i.edit) {
                        this.$message.warning('请先保存当前编辑项')
                        return true
                    }
                }
                return false
            },
            validate(row) {
                // 数据校验
                if (!row.edit) {
                    this.$message.warning('当前行没有处于可编辑状态')
                    return false
                }
                if (row.title.trim() === '') {
                    this.$message.warning('标题不能为空')
                    return false
                }
                if (row.description.trim() === '') {
                    this.$message.warning('描述不能为空')
                    return false
                }
                if (row.imgUrl.trim() === '') {
                    this.$message.warning('图片不能为空')
                    return false
                }
                if (row.stock <= 0) {
                    this.$message.warning('库存必须大于0')
                    return false
                }
                if (row.price <= 0) {
                    this.$message.warning('价格必须大于0')
                    return false
                }
                return true
            }
        }
    }
</script>
<style scoped>
    .img-size {
        width: 60px;
    }
    .el-table-add-row {
        margin-top: 10px;
        width: 100%;
        height: 34px;
        border: 1px dashed #c1c1cd;
        border-radius: 3px;
        cursor: pointer;
        justify-content: center;
        display: flex;
        line-height: 34px;
    }

</style>
